#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include "SerialPort.h"

#define STR_LEN 128

typedef struct
{
	unsigned int slot;
	unsigned int on_off;
	unsigned int speed;
	unsigned int power_on;
	unsigned int power_down;
	char port[STR_LEN];
}proc_data_t;

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
proc_data_t g_data;

int main(int argc, char *argv[])
{
	int ret;
	int cnt;
	char pListStr[16][16];
	char str[64] = {0};

	memset(&g_data, 0, sizeof(proc_data_t));
	if(argc > 1)
	{
		if(argc > 2)
		{
			//printf("argc:%d,argv[1]:%s,argv[2]:%s\r\n", argc,(char *)argv[1], (char *)argv[2]);
			g_data.slot = (argv[2][0]-'0');
			if(argc > 3)
			{
				//printf("argc:%d,argv[1]:%s,argv[2]:%s\r\n", argc,(char *)argv[1], (char *)argv[2]);
				g_data.on_off = (argv[3][0]-'0');
			}
			else
			{
				//printf("argc:%d,argv[1]:%s\r\n", argc,(char *)argv[1]);
				g_data.on_off = 0;
			}
		}
		else
		{
			//printf("argc:%d,argv[1]:%s\r\n", argc,(char *)argv[1]);
			g_data.slot = 0;
			g_data.on_off = 0;
		}
		strcpy(g_data.port, argv[1]);
	}
	else
	{
		printf("No COM paramater, Default COM24, slot:0 off\r\n");
		memcpy(g_data.port, "COM24", 5);
	}
	g_data.speed = 9600;
	g_data.power_on = 0xA00100A0+((g_data.slot+1)*0x100)+((g_data.slot+2)*0x1000000);//0xA10001A0;
	g_data.power_down = 0xA00000A0+((g_data.slot+1)*0x100)+((g_data.slot+1)*0x1000000);//0xA20101A0;

	printf("Switch Uart:%s slot:%d %s\r\n", 
			g_data.port, g_data.slot, g_data.on_off ? "off":"on");
	SerialPort();
//	cnt = GetPortList(pListStr);
//	for (int i = 0; i < cnt; i++)
//		printf("%s\r\n", (LPTSTR)pListStr[i]);

	if (TRUE == OpenPort((LPTSTR)g_data.port, g_data.speed, 8, NOPARITY, ONESTOPBIT))
	{
		if(g_data.on_off)
		{
			memcpy(str, (void *)&g_data.power_down, 4);
			//printf("power_off\r\n");				
		}
		else
		{
			memcpy(str, (void *)&g_data.power_on, 4);
			//printf("power_on\r\n");
		}
		ret = Write((LPBYTE)str, 4);
		ClosePort();
	}
	else
	{
		printf("OpenPort FAIL!\r\n");
	}
	return 0;
}
